document.addEventListener('click', (event) => {
    closeBookSettings(event);
    openBookSettings(event);
    makeBookReadOrNotRead(event);
    makeBookDeferredOrUrgent(event);
    removeBook(event);
    showListOfGroups(event);
    changeGroup(event);
    changeTitleOfBook(event);
    changeDescriptionOfBook(event);
    showWindowForChanginAuthor(event);
    changeAuthorOfBook(event);
    showWindowForChangingCoverOfBook(event);
    showWindowForChangingBackgroundImageOfBook(event);
    changeCoverOfBook(event);
    changeBackgroundImageOfBook(event);
})

document.querySelectorAll('[data-input-to-change-book]').forEach(element => {
    element.addEventListener('mouseenter', changeSomethingInBook.bind(this))
})

document.addEventListener('change', event => {
    selectCoverImage(event);
})



function changeBackgroundImageOfBook(event) {
    if (!event.target.closest('[data-change-book-background-image]')) return;
    event.preventDefault();

    const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
    const url = document.location.href + '?change_background_image=true';
    const fileName = document.querySelector('#input-file').files[0].name;
    const fileData = document.querySelector('#input-file').files[0];
    const fileObject = {'token': token, 'fileData': fileData, 'fileName': fileName};
    base.sendAjaxRequest(url, 'POST', body=null, file=fileObject)

    setTimeout(() => {
        document.querySelector('[data-temporary-window]').remove();
    }, 200)
}

function changeCoverOfBook(event) {
    if (!event.target.closest('[data-change-book-cover]')) return;
    event.preventDefault();

    const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
    const url = document.location.href + '?change_cover=true';
    const fileName = document.querySelector('#input-file').files[0].name;
    const fileData = document.querySelector('#input-file').files[0];
    const fileObject = {'token': token, 'fileData': fileData, 'fileName': fileName};
    base.sendAjaxRequest(url, 'POST', body=null, file=fileObject)
        .then(result => {
            document.querySelector('.description-big>img').src = result.image_url;
        })

    makePossibleToHideWindow()


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function makePossibleToHideWindow() {
        // Добавляем обработчик чтобы окно могло скрываться

        setTimeout(() => {
            document.querySelector('[data-temporary-window]').remove();
        }, 200)
    }
}


function selectCoverImage(event) {
    if (!event.target.closest('[data-change-book-cover-button]')) return;
    if (!document.querySelector('#input-file').value) return;

    changeAppearance()


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function changeAppearance() {
        let fileName = document.querySelector('#input-file').files[0].name;
        if (fileName.length >= 19) fileName = fileName.substr(0, 18) + '...';
        document.querySelector('span.name-of-selected-file').innerHTML = fileName;
    }
}


function showWindowForChangingBackgroundImageOfBook(event) {
    if (!event.target.closest('[data-change-background-image]')) return;
    if (document.querySelector('.cover-selection-window')) return;

    const windowForChangingBackgroundImage = base.getCoverSelectionWindow();

    replaceSomeElements(windowForChangingBackgroundImage);
    addWindow(windowForChangingBackgroundImage);
    setPosition(windowForChangingBackgroundImage);
    addHint();


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function setPosition(window) {
        window.style.left = window.clientWidth - 50 + 'px';
        window.style.top = -window.clientHeight / 2 + 'px';
    }

    function addWindow(window) {
        document.querySelector('[data-change-background-image]').insertAdjacentElement('beforeend', window);
    }

    function replaceSomeElements(window) {
        const explanatoryText = getExplanatoryText();
        const confirmationButton = getConfirmationButton();


        window.querySelector('form[name="change-book-cover"] button[type="submit"]')
            .replaceWith(confirmationButton)

        window.querySelector('form[name="change-book-cover"]>p')
            .replaceWith(explanatoryText)
    }
    
    function addHint() {
        document.querySelector('form[name="change-book-cover"]>p').insertAdjacentHTML('afterend', `
            <p data-hint-for-background-image>
                Для корректного отображения размер изображения должен быть не менее ${window.innerWidth}x${window.innerHeight}
            </p>
        `)
    }

    function getConfirmationButton() {
        const confirmationButton = document.createElement('button');
        confirmationButton.setAttribute('type', 'submit');
        confirmationButton.setAttribute('data-change-book-background-image', 'true');
        confirmationButton.textContent = 'Изменить фон';
        return confirmationButton
    }

    function getExplanatoryText() {
        const explanatoryText = document.createElement('p');
        explanatoryText.className = 'background-image-explanatory-text';
        explanatoryText.textContent = 'Выберите фоновое изображение';
        return explanatoryText;
    }
}


function showWindowForChangingCoverOfBook(event) {
    if (!event.target.closest('[data-change-cover]')) return;
    if (document.querySelectorAll('.cover-selection-window').length > 0) return;
    
    const coverSelectionWindow = base.getCoverSelectionWindow();
    event.target.insertAdjacentElement('beforeend', coverSelectionWindow);
    setPosition(event, coverSelectionWindow);

    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function makePossibleToHideWindow(window) {
        // Добавляем обработчик чтобы окно могло скрываться

        window.addEventListener('mouseleave', event => {
            event.target.remove();
        })
    }

    function setPosition(event, coverSelectionWindow) {
        coverSelectionWindow.style.left = event.target.parentElement.clientWidth + 3 + 'px';
        coverSelectionWindow.style.top = -(coverSelectionWindow.clientHeight / 2) + 'px';
    }
}

function changeAuthorOfBook(event) {
    if (!event.target.closest('[data-author-from-list]')) return;

    const authorFromListSlug = event.target.dataset.authorFromList;
    const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
    const url = document.location.href;
    const body = {'token': token, 'new_author_name': authorFromListSlug};

    base.sendAjaxRequest(url, 'POST', body);
    console.log(event.target.textContent)
    closeFormToChangeAuthorOfBook(event);


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function closeFormToChangeAuthorOfBook(event) {
        document.querySelector('[data-author-of-book]').textContent = `Автор: ${event.target.textContent}`;
        document.querySelector('.list-of-authors-window').remove();
    }
}


function showWindowForChanginAuthor(event) {
    // Показываем окно для смены автора книги

    if (!event.target.closest('.change-author-of-book')) return;
    
    const listOfAuthorsWindow = getListOfAuthorsWindow();
    insertWindowToSelectAuthor(listOfAuthorsWindow);
    addData(listOfAuthorsWindow)
    setPosition();


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function addData() {
        const url = document.location.origin + '/author/actions/list_of_authors/';
        base.sendAjaxRequest(url, 'GET')
            .then(result => {
                // Вставляем полученные данные
                for (const author of Object.values(result)) {
                    document.querySelector('.list-of-authors-window').insertAdjacentHTML('beforeend', `
                        <span data-author-from-list="${author[1]}">${author[0]}</span>
                    `)
                }
            })

    }

    function setPosition() {
        
        const listOfAuthorsWindow = document.querySelector('.list-of-authors-window');
        console.log('loaw', listOfAuthorsWindow.clientWidth)
        listOfAuthorsWindow.style.left = -195 + 'px';
        listOfAuthorsWindow.style.top = '0px';
    }

    function insertWindowToSelectAuthor(windowToSelectAuthor) {
        const buttonToChangeBookAuthor = document.querySelector('.change-author-of-book');
        buttonToChangeBookAuthor.insertAdjacentElement('beforeend', windowToSelectAuthor)
    }

    function getListOfAuthorsWindow() {
        const listOfAuthorsWindow = document.createElement('div');
        listOfAuthorsWindow.className = 'list-of-authors-window';
        return listOfAuthorsWindow;
    }
}

function changeDescriptionOfBook(event) {
    // Меняем описание книги

    if (!event.target.closest('.change-description-of-book')) return;
    if (document.querySelector('form[name=change-description-of-book-form]')) return;

    const oldContent = document.querySelector('[data-book-description-text]');
    const oldContentFullText = oldContent.innerHTML;
    const oldContentText = oldContentFullText.replace('Описание: ', '');
    const newContent = `Описание: 
    <form name="change-description-of-book-form">
        <div data-change-description-of-book-button-actions>
            <span data-change-description-of-book-button="true" data-change-description-of-book-button-ok>
                <i class="fa-solid fa-check"></i>
            </span>
            <span data-change-description-of-book-button="true" data-change-description-of-book-button-close>
                <i class="fa-solid fa-xmark"></i>
            </span>
        </div>
        <textarea data-new-book-description>
            ${oldContentText}
        </textarea>
    </form>
    `
    oldContent.innerHTML = newContent;
    closeFormToChangeDescriptionOfBook(oldContent, oldContentText);
    confirmChangedData(oldContent)

    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function confirmChangedData(oldContent) {
        document.querySelector('[data-change-description-of-book-button-ok]').addEventListener('click', event => {
            const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
            const newBookDescription = document.querySelector('form[name="change-description-of-book-form"]>textarea').value;
            const body = {'token': token, 'new_book_description': newBookDescription};
            const url = document.location.href;
            base.sendAjaxRequest(url, 'POST', body);
            oldContent.innerHTML = `Описание: ${newBookDescription}`;
        })

    }

    function closeFormToChangeDescriptionOfBook(oldContent, oldContentFullText) {
        document.querySelector('[data-change-description-of-book-button-close]').addEventListener('click', event => {
            console.log('oldsf', oldContent.innerHTML)
            oldContent.innerHTML = 'Описание: ' + oldContentFullText;
            document.querySelector('.change-description-of-book').remove();
        })
    }
}

function changeTitleOfBook(event) {
    // Меняем название книги

    if (!event.target.closest('.change-title-of-book')) return;
    const oldContent = document.querySelector('.title-big>span[data-title-of-book="true"]');
    const oldContentText = oldContent.innerHTML;
    const oldContentTitleOfBook = oldContent.textContent.replace('Название: ', '');
    const newContent = `Название: 
        <form name="change-title-of-book-form">
            <input value="${oldContentTitleOfBook}" data-new-book-title>
            <span data-change-title-of-book-button="true" data-change-title-of-book-button-ok>
                <i class="fa-solid fa-check"></i>
            </span>
            <span data-change-title-of-book-button="true" data-change-title-of-book-button-close>
                <i class="fa-solid fa-xmark"></i>
            </span>
        </form>
    `;
    oldContent.innerHTML = newContent;

    confirmChangedData(oldContent);
    closeFormToChangeTitleOfBook(oldContent, oldContentText);


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function confirmChangedData(oldContent) {
        document.querySelector('[data-change-title-of-book-button-ok]').addEventListener('click', event => {
            const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
            const newBookTitle = document.querySelector('[data-new-book-title]').value;
            const body = {'token': token, 'new_book_title': newBookTitle};
            const url = document.location.href;
            base.sendAjaxRequest(url, 'POST', body);
            oldContent.innerHTML = `Название: ${newBookTitle}`;
        })

    }

    function closeFormToChangeTitleOfBook(oldContent, oldContentText) {
        document.querySelector('[data-change-title-of-book-button-close]').addEventListener('click', event => {
            oldContent.innerHTML = oldContentText;
        })

    }

}


function changeSomethingInBook(event) {
    // Меняем что-то в книге

    if (document.querySelectorAll('.change-author-of-book').length > 0) return;
    if (document.querySelectorAll('.change-description-of-book').length > 0) return;

    const buttonForChangingBookElement = document.createElement('div');
    buttonForChangingBookElement.className = 'button-to-change-something-in-book';

    if (event.target.closest('[data-input-to-change-book="title"]')) {
        buttonForChangingBookElement.classList.add('change-title-of-book');
        buttonForChangingBookElement.innerHTML = `
            <i class="fa-solid fa-pen"></i>
        `
        showButtonForChangingBook(event, buttonForChangingBookElement);
    } else if(event.target.closest('[data-input-to-change-book="author"]')) {
        buttonForChangingBookElement.classList.add('change-author-of-book');
        buttonForChangingBookElement.innerHTML = `
            <i class="fa-solid fa-user"></i>
        `
        showButtonForChangingBook(event, buttonForChangingBookElement);
    } else if(event.target.closest('[data-input-to-change-book="description"]')) {
        buttonForChangingBookElement.classList.add('change-description-of-book');
        buttonForChangingBookElement.innerHTML = `
            <i class="fa-solid fa-pen"></i>
        `
        showButtonForChangingBook(event, buttonForChangingBookElement);
    }


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function showButtonForChangingBook(event, buttonForChangingBookElement) {
        setTimeout(() => {
            if (document.querySelectorAll('.change-title-of-book').length > 0) return;
            event.target.insertAdjacentElement('beforeend', buttonForChangingBookElement)
        }, 500)

        finishChangingTitleOfBook(event, buttonForChangingBookElement)


        // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        function finishChangingTitleOfBook(event, buttonForChangingBookElement) {
            event.target.closest('[data-input-to-change-book]').addEventListener('mouseleave', event => {
                setTimeout(() => {
                    buttonForChangingBookElement.remove();
                }, 500)
            })
        }
    }
}



function changeGroup(event) {
    // Меняем группу

    if (!event.target.closest('[data-group')) return;
    const groupNameButton = event.target.closest('[data-group]');
    const url = document.location.href;
    const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
    const body = {'token': token, 'group_name': groupNameButton.dataset.group};
    base.sendAjaxRequest(url, 'POST', body);
    changeAppearance(groupNameButton);


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ
    
    function changeAppearance(groupNameButton) {
        setTimeout(() => {
            document.querySelector('.group-big').innerHTML = `Группа: ${groupNameButton.textContent}`
            document.querySelector('.group-selection-window').remove()
        }, 200)
    }
}

function showListOfGroups(event) {
    // Показываем список групп
    if (!event.target.closest('[data-list-of-groups]')) return

    changeAppearance(event);
    const windowForSelectingGroup = base.getWindowForSelectingGroup();
    const bookSettingsWindow = document.querySelector('.book-settings-window');
    bookSettingsWindow.insertAdjacentElement('beforeend', windowForSelectingGroup);
    const groupData = getGroupData();
    setPosition(windowForSelectingGroup);

    addHandlerForClosing(windowForSelectingGroup, event);

    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function addHandlerForClosing(windowForSelectingGroup, event) {
        document.querySelector('.group-selection-window').onmouseleave = (event) => {
            setTimeout(() => {
                windowForSelectingGroup.remove();
                document.querySelector('[data-list-of-groups]').style.background = 'white';
            }, 300)
        }
    }

    function setPosition(window) {
        const bookSettingsWindow = document.querySelector('.book-settings-window');
        window.style.left = bookSettingsWindow.clientWidth + 5 + 'px';
        window.style.top = 60 + 'px';
    }

    function getGroupData() {
        // Получаем данные групп

        const url = document.location.origin + '/group/actions/?list_of_groups=true';

        base.sendAjaxRequest(url, 'GET')
            .then(result => {
                console.log('result', result)
                insertData(result)
            })
    }

    function insertData(data) {
        const $listOfGroups = document.querySelector('.group-selection-window>.list-of-groups');

        console.log(Object.values(data))

        for (const group of Object.values(data)) {
            $listOfGroups.insertAdjacentHTML('beforeend', `
                <span data-group="${group[1]}">${group[0]}</span>
            `)
        }
    }

    function changeAppearance(event) {
        event.target.closest('[data-list-of-groups]').style.background = '#f1f1f1';
    }

}


function removeBook(event) {
    const removeBookButton = event.target.closest('[data-remove-book]');
    if (!removeBookButton) return;
    event.preventDefault();
    const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
    const body = {'token': token, 'delete_book': 'true'}
    base.sendAjaxRequest(document.location.href, 'POST', body)
    const url = document.location.origin + '/library/';
    document.location.href = url;

    document.addEventListener('DOMContentloaded', (event) => {
        document.location.reload();
    })
}

function makeBookDeferredOrUrgent(event) {
    // Делаем книгу отложенной или наоборот
    
    if (!event.target.closest('[data-deferred]')) return;
    const result = checkBookIsDeffered();

    result ? sendRequestMakeBookDeferredOrUrgent('urgent') : sendRequestMakeBookDeferredOrUrgent('deferred')
}

function sendRequestMakeBookDeferredOrUrgent(status) {
    // Отправляем запрос для того чтобы сделать книгу отложенной или наоборот
    
    const url = document.location.href;
    const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
    body = {'token': token}

    if (status == 'urgent') {
        body['urgent'] = 'true'
        changeAppearance('urgent')
    } else if (status == 'deferred') {
        body['deferred'] = 'true'
        changeAppearance('deferred')
    }

    base.sendAjaxRequest(url, 'POST', body);


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function changeAppearance(status) {
        const isDeferInput = document.querySelector('[data-is-defer]');
        if (status == 'urgent') {
            isDeferInput.dataset.isDefer = 'False';
            isDeferInput.innerHTML = 'Отложена: Нет'
            document.querySelector('form[name="defer-book"]').style.color = '#898989';
        } else if (status == 'deferred') {
            isDeferInput.dataset.isDefer = 'True';
            isDeferInput.innerHTML = 'Отложена: Да'
            document.querySelector('form[name="defer-book"]').style.color = '#ff2828';
        }
    }
}

function closeBookSettings(event) {
    if (getBookSettingsIsOpen() &&
        !event.target.closest('.book-settings-window')) {

        const bookSettings = getBookSettingsIsOpen();
        bookSettings.classList.add('hide-element');
        setTimeout(() => {
            bookSettings.remove()
        }, 1000)
    }
}


function makeBookReadOrNotRead(event) {
    // Делаем книгу прочитанной или наоборот
    
    if (event.target.closest('[data-put-book]')) {
        event.preventDefault();
        if (checkBookIsRead()) {
            base.indicateReadingStatus('unread')
            sendRequestMakeBookReadOrUnread('unread');
        } else {
            base.indicateReadingStatus('read')
            sendRequestMakeBookReadOrUnread('read');
        }
    }

    function sendRequestMakeBookReadOrUnread(status) {
        // Отправляем запрос для того чтобы пометить книгу как прочитанной или наоборот

        const url = document.location.href
        const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
        body = {'token': token}

        if (status == 'unread') {
            body['make_book_unread'] = 'true'
        } else if (status == 'read') {
            body['make_book_read'] = 'true'
        }

        base.sendAjaxRequest(url, 'POST', body);
    }
}


function openBookSettings(event) {
    // Открываем настройки книги

    if (event.target.closest('[data-open-book-settings') &&
        document.querySelectorAll('.book-settings-window').length == 0) {

        const $bookSettingsButton = document.querySelector('[data-open-book-settings]');
        const bookSettingsWindow = getBookSettingsWindow();
        $bookSettingsButton.insertAdjacentElement('beforeend', bookSettingsWindow);
        setPositionbookSettingsWindow(bookSettingsWindow);
        displayStatusOfBook(event);
    }


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function setPositionbookSettingsWindow(bookSettingsWindow) {
        // Устанавливаем позицию для окна настроек книги

        bookSettingsWindow.style.top = -bookSettingsWindow.clientHeight - 10 + 'px';
        bookSettingsWindow.style.left = -(bookSettingsWindow.clientWidth / 2) + 'px';
    }

    function displayStatusOfBook() {
        const isRead = document.querySelector('[data-is-read]').dataset.isRead
        const isDefer = document.querySelector('[data-is-defer]').dataset.isDefer

        if (isRead == 'True') {
            base.indicateReadingStatus('read');
        } else if (isRead == 'False')
            base.indicateReadingStatus('unread');

        if (isDefer == 'True') {
            document.querySelector('form[name="defer-book"]').style.color = '#ff2828';
        } else if (isDefer == 'False') {
            document.querySelector('form[name="defer-book"]').style.color = '#898989';
        }
    }
}


function getBookSettingsWindow() {
    // Получаем окно настроек книги

    const bookSettingsWindow = document.createElement('div');
    bookSettingsWindow.className = 'book-settings-window';
    const basicHtml = `
        <div class="book-settings-window-content">
            <div class="finished-book action-on-button" data-put-book="true">
                <form name="finished-book">
                    <i class="fa-solid fa-check"></i>
                    <span>Прочитана</span>
                </form>
            </div>
            <div class="put-book action-on-button" data-deferred="true">
                <form name="defer-book">
                    <i class="fa-solid fa-ban"></i>
                    <span>Отложить книгу</span>
                </form>
            </div>
            <div class="change-cover action-on-button" data-change-cover="true">
                <span>
                    <i class="fa-solid fa-camera"></i>
                </span>
                <span>Изменить обложку</span>
            </div>
            <div class="change-cover action-on-button" data-change-background-image="true">
                <span>
                    <i class="fa-solid fa-image"></i>
                </span>
                <span>Фоновое изображение</span>
            </div>
            <div class="update-book action-on-button" data-list-of-groups="true">
                <div class="update-book-main">
                    <span>
                        <i class="fa-solid fa-pen-to-square" data-color></i>
                    </span>
                    <span>Изменить группу </span>
                </div>
                <span>ᐅ</span>
            </div>
            <div class="remove-book action-on-button" data-remove-book="true">
                <form name="remove-book">
                    <span>
                        <i class="fa-solid fa-trash" data-color></i>
                    </span>
                    <span data-remove-book="true">
                        Удалить книгу
                    </span>
                </form>
            </div>
        </div>
    `
    bookSettingsWindow.insertAdjacentHTML('beforeend', basicHtml);

    return bookSettingsWindow;
}

function checkBookIsRead() {
    // Проверяем прочитана ли книга

    const isRead = document.querySelector('[data-is-read]').dataset.isRead

    if (isRead == 'True') {
        return true
    } else {
        return false
    }
}

function checkBookIsDeffered() {
    // Проверяем отложена ли книга

    const isDeferred = document.querySelector('[data-is-defer]').dataset.isDefer;
    return isDeferred == 'True' ? true : false;
}

function getBookSettingsIsOpen() {
    // Проверяем открыто ли окно с настройками книги

    return document.querySelector('.book-settings-window') 
}